package info.decisionnelle;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import weka.classifiers.Classifier;
import weka.classifiers.bayes.NaiveBayes;
import weka.core.Instance;
import weka.core.Instances;

/**
 * 
 */
public class WekaAnalyzer {
	private static Classifier cModel;
	private static Instance instance;
	
	public static double analyzeWithWeka(DemandeDeCredit ddeC) {
		BufferedReader reader = null;
		Instances data = null;
		double result = -1;
		
		cModel = null;
		instance = null;
		try {
                    
			// Chargement du arff
			reader = new BufferedReader(new FileReader("./GermanScoring/credit-g.arff"));
			data = new Instances(reader);
			reader.close();

			data.setClassIndex(20);

			// Definition de l'instance
			instance = new Instance(21);
			instance.setValue(data.attribute(0), ddeC.getChecking_status());
			instance.setValue(data.attribute(1), ddeC.getDuration());
			instance.setValue(data.attribute(2), ddeC.getCredit_history());
			instance.setValue(data.attribute(3), ddeC.getPurpose());
			instance.setValue(data.attribute(4), ddeC.getCredit_amount());
			instance.setValue(data.attribute(5), ddeC.getSavings_status());
			instance.setValue(data.attribute(6), ddeC.getEmployment());
			instance.setValue(data.attribute(7),
					ddeC.getInstallment_commitment());
			instance.setValue(data.attribute(8), ddeC.getPersonal_status());
			instance.setValue(data.attribute(9), ddeC.getOther_parties());
			instance.setValue(data.attribute(10), ddeC.getResidence_since());
			instance.setValue(data.attribute(11), ddeC.getProperty_magnitude());
			instance.setValue(data.attribute(12), ddeC.getAge());
			instance.setValue(data.attribute(13), ddeC.getOther_payment_plans());
			instance.setValue(data.attribute(14), ddeC.getHousing());
			instance.setValue(data.attribute(15), ddeC.getExisting_credits());
			instance.setValue(data.attribute(16), ddeC.getJob());
			instance.setValue(data.attribute(17), ddeC.getNum_dependents());
			instance.setValue(data.attribute(18), ddeC.getOwn_telephone());
			instance.setValue(data.attribute(19), ddeC.getForeign_worker());

			// Construction du classifier
			cModel = (Classifier) new NaiveBayes();
			cModel.buildClassifier(data);

			// Classify instance
			instance.setDataset(data);
			result = cModel.classifyInstance(instance);
			System.out.println(result);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * Get the distribution for instance
	 */
	public static double[] getDistributionForInstance() {
		try {
			return cModel.distributionForInstance(instance);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
